<template>
  <view class="container">
 
    
    <view class="feedback-list">
      <view v-if="loading" class="loading">
        <view class="loading-spinner"></view>
      </view>
      
      <view v-else-if="feedbackList.length === 0" class="empty-data">
        <view class="empty-icon">
          <text class="iconfont">&#xe67e;</text>
        </view>
        <text class="empty-text">暂无反馈记录</text>
      </view>
      
      <view v-else>
        <view class="refresh-info" v-if="lastRefreshTime">
          <text>上次刷新: {{ lastRefreshTime }}</text>
        </view>
        <view v-for="(item, index) in feedbackList" :key="index" class="feedback-item" @click="goToDetail(item.id || item.feedback_id)">
          <view class="feedback-title">
            <text>{{ item.title }}</text>
            <view :class="['status-tag', getStatusClass(item.status)]">{{ getStatusText(item.status) }}</view>
          </view>
          <view class="feedback-content">{{ item.content }}</view>
          <view class="feedback-footer">
            <text class="feedback-time">{{ formatDate(item.created_at) }}</text>
            <view v-if="item.status === 'PENDING'" class="operation-btns">
              <button class="btn btn-primary" @click.stop="goToEdit(item.id || item.feedback_id)">编辑</button>
              <button class="btn btn-danger" @click.stop="handleDelete(item.id || item.feedback_id)">删除</button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="add-btn">
      <navigator url="/pages/feedback/add-new" hover-class="navigator-hover">
        <button class="btn btn-primary btn-block">提交新反馈</button>
      </navigator>
    </view>
  </view>
</template>

<script>
import { getFeedbackList, deleteFeedback } from '@/api/services.js'
import eventBus from '@/utils/eventBus.js'

export default {
  data() {
    return {
      feedbackList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      lastRefreshTime: ''
    }
  },
  onLoad() {
    this.loadFeedbackList()
    // 监听刷新事件
    eventBus.on('refreshFeedbackList', this.handleRefresh)
  },
  onUnload() {
    // 移除事件监听
    eventBus.off('refreshFeedbackList', this.handleRefresh)
  },
  onPullDownRefresh() {
    this.page = 1
    this.loadFeedbackList().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    if (this.feedbackList.length < this.total) {
      this.page++
      this.loadFeedbackList()
    }
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    loadFeedbackList() {
      if (this.loading) return Promise.resolve()
      
      this.loading = true
      return getFeedbackList({
        page: this.page,
        size: this.pageSize // 后端API使用size而不是pageSize
      })
        .then(res => {
          console.log('获取反馈列表响应:', res)
          if (res.code === 200) {
            const { list, total } = res.data
            
            if (this.page === 1) {
              this.feedbackList = list
            } else {
              this.feedbackList = [...this.feedbackList, ...list]
            }
            
            this.total = total
            
            // 更新刷新时间
            const now = new Date()
            this.lastRefreshTime = this.formatTime(now)
          } else {
            uni.showToast({
              title: res.message || '获取反馈列表失败',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          console.error('获取反馈列表失败', err)
          uni.showToast({
            title: '获取反馈列表失败',
            icon: 'none'
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    getStatusClass(status) {
      switch (status) {
        case 'PENDING':
          return 'status-pending'
        case 'RESOLVED':
          return 'status-resolved'
        default:
          return ''
      }
    },
    
    getStatusText(status) {
      switch (status) {
        case 'PENDING':
          return '待处理'
        case 'RESOLVED':
          return '已解决'
        default:
          return '未知'
      }
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    formatTime(date) {
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${hours}:${minutes}:${seconds}`
    },
    
    addFeedback() {
      console.log('addFeedback method called');
      try {
        uni.navigateTo({
          url: '/pages/feedback/add-new',
          fail: (err) => {
            console.error('Navigation failed:', err);
            // Try an alternative approach
            uni.redirectTo({
              url: '/pages/feedback/add-new',
              fail: (err2) => {
                console.error('Redirect also failed:', err2);
              }
            });
          }
        });
      } catch (err) {
        console.error('Error in navigation:', err);
      }
    },
    
    goToAdd() {
      console.log('goToAdd method called');
      uni.navigateTo({
        url: '/pages/feedback/add-new'
      })
    },
    
    goToEdit(id) {
      uni.navigateTo({
        url: `/pages/feedback/edit?id=${id}`
      })
    },
    
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/feedback/detail?id=${id}`
      })
    },
    
    handleDelete(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除此反馈吗？',
        success: res => {
          if (res.confirm) {
            deleteFeedback(id)
              .then(res => {
                if (res.code === 204) {
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  })
                  this.page = 1
                  this.loadFeedbackList()
                } else {
                  uni.showToast({
                    title: res.message || '删除失败',
                    icon: 'none'
                  })
                }
              })
              .catch(err => {
                console.error('删除反馈失败', err)
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              })
          }
        }
      })
    },
    
    // 处理刷新事件
    handleRefresh() {
      console.log('收到刷新反馈列表事件')
      this.page = 1
      this.loadFeedbackList()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 120rpx;
}

.navbar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 0 30rpx;
  
  &-left {
    width: 60rpx;
    display: flex;
    align-items: center;
  }
  
  &-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 36rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-back:before {
  content: "\e679";
}

.feedback-list {
  padding: 20rpx;
}

.refresh-info {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  padding: 10rpx;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  
  &-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-data {
  margin-top: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
  }
}

.feedback-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.feedback-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
  
  text {
    font-size: 32rpx;
    font-weight: bold;
    flex: 1;
  }
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  color: #ffffff;
}

.status-pending {
  background-color: #3498db;
}

.status-resolved {
  background-color: #2ecc71;
}

.feedback-content {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.feedback-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.operation-btns {
  display: flex;
  gap: 20rpx;
}

.btn {
  font-size: 24rpx;
  padding: 6rpx 20rpx;
  border-radius: 6rpx;
  border: none;
  color: #ffffff;
  
  &-primary {
    background-color: #2979ff;
  }
  
  &-danger {
    background-color: #dd524d;
  }
  
  &-block {
    width: 100%;
    height: 80rpx;
    font-size: 32rpx;
  }
}

.add-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
}

.navigator-hover {
  opacity: 0.8;
}
</style> 